<template>
  <view class="order-usage">
    <view class="qr-code-container" @click="toggleMosaic">
      <image v-if="qrCodeImage && isMosaic" :src="mosaicImage" class="qr-code-image" />
      <image v-else-if="qrCodeImage && !isMosaic" :src="qrCodeImage" class="qr-code-image" />
      <view v-else class="loading">生成中...</view>
    </view>
    <button class="refresh-button" @click="generateQRCode">刷新二维码</button>
  </view>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import QRCode from 'qrcode';

export default defineComponent({
  setup() {
    const qrCodeImage = ref<string | null>(null);
    const mosaicImage = ref<string | null>(null);
    const isMosaic = ref(true);

    const generateQRCode = async () => {
      try {
        const url = 'https://example.com/order/12345'; // 替换为实际的订单URL
        qrCodeImage.value = await QRCode.toDataURL(url);
        // 生成马赛克版本的二维码
        mosaicImage.value = await QRCode.toDataURL(url, { errorCorrectionLevel: 'H', maskPattern: 0 });
      } catch (error) {
        console.error('生成二维码失败:', error);
      }
    };

    const toggleMosaic = () => {
      isMosaic.value = !isMosaic.value;
    };

    onMounted(() => {
      generateQRCode();
    });

    return {
      qrCodeImage,
      mosaicImage,
      isMosaic,
      generateQRCode,
      toggleMosaic,
    };
  },
});
</script>

<style scoped>
.order-usage {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.qr-code-container {
  margin-bottom: 20px;
}

.qr-code-image {
  width: 200px;
  height: 200px;
}

.loading {
  font-size: 16px;
  color: #999;
}

.refresh-button {
  padding: 10px 20px;
  font-size: 16px;
  color: #fff;
  background-color: #007aff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.refresh-button:active {
  background-color: #0056b3;
}
</style>